﻿using System;
using System.Runtime.CompilerServices;
using System.Threading;
using Core.Base.Module;
using Core.Mgr;
using Core.Mgrs;
using DG.Tweening;
using Logic.Global.UI;
using Logic.Main;
using Model;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

namespace Logic.Global
{
    /// <summary>
    /// 全局模块，永远不会被卸载
    /// </summary>
    [Module("Main")]
    public class MainModule : BaseModule
    {
        /// <summary>
        /// 是否为首次加载全局模块
        /// </summary>
        private static bool _isFirstLoad = true;

        public override void OnLoadStart(ModuleAttribute moduleAttribute, ITuple tuple = null, Action onFinish = null,
            Action onFail = null)
        {
            base.OnLoadStart(moduleAttribute, tuple, onFinish, onFail);
            if (_isFirstLoad) // 首次加载GlobalModule，初始化游戏
            {
                _isFirstLoad = false;
                Debug.unityLogger.logEnabled = AppConst.Environment == Environment.Dev;
                AudioMgr.Ins.OnInit();
                AdMgr.Ins.OnInit();
                DaDianMgr.OnInit();
                UIMgr.Ins.OnInit();
                QualityAdapt();
                UserDataModel.OnInit();
                UIMgr.Ins.OnOpen<HomeUI>(
                    openedCb: delegate { GameObject.Find("SplashImage")?.SetActive(false); });
            }
            else
            {
                SceneManager.LoadSceneAsync("Empty");
                AudioMgr.Ins.StopAllSound();
                UIMgr.Ins.OnOpen<HomeUI>();
            }
        }

        public override void OnUnload()
        {
            base.OnUnload();
        }

        /// <summary>
        /// 质量适配，根据手机性能改变帧率及画面质 量
        /// </summary>
        void QualityAdapt()
        {
            if (SystemInfo.systemMemorySize <= 2100 &&
                Application.platform == RuntimePlatform.Android) //当内存小于2100M时，判断为低端机，降低性能
            {
                Debug.Log($"系统内存：{SystemInfo.systemMemorySize}M，自动降低质量");
                Application.targetFrameRate = 30;
                QualitySettings.SetQualityLevel(0, true);
            }
            else
            {
                Application.targetFrameRate = 60;
            }
        }
    }
}